/**
 *
 */
package com.ts.common.controller;

import com.ts.common.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Ivy
 */
@Controller
@RequestMapping("/templates")
public class PageController {

    @GetMapping("/{first}")
    public String to(@PathVariable("first") String first, HttpServletRequest request, Model model) {
        setParams(request, model);
        return first;
    }

    @GetMapping("/{first}/{second}")
    public String to(@PathVariable("first") String first, @PathVariable("second") String second, HttpServletRequest request, Model model) {
        setParams(request, model);
        return String.format("%s/%s", first, second);
    }

    @GetMapping("/{first}/{second}/{third}")
    public String to(@PathVariable("first") String first, @PathVariable("second") String second, @PathVariable("third") String third, HttpServletRequest request, Model model) {
        setParams(request, model);
        return String.format("%s/%s/%s", first, second, third);
    }

    @GetMapping("/{first}/{second}/{third}/{fourth}")
    public String to(@PathVariable("first") String first, @PathVariable("second") String second, @PathVariable("third") String third, @PathVariable("fourth") String fourth, HttpServletRequest request, Model model) {
        setParams(request, model);
        return String.format("%s/%s/%s/%s", first, second, third, fourth);
    }

    private void setParams(HttpServletRequest request, Model model) {
        Map<String, String[]> map = request.getParameterMap();
        for (String key : map.keySet()) {
            model.addAttribute(key, StringUtils.join(map.get(key)));
        }
    }
}
